module com
{
	export class NetManager
	{
		private static _instance:NetManager;
		public static getInstance():NetManager
		{
			if(this._instance == null)
			{
				this._instance = new NetManager();
			}
			return this._instance;
		}

		private socketDic:Dictionary;
        private _connectCallBack: Function;
        private _connectThisObject: any;


		public constructor()
		{
			this.socketDic = new Dictionary();
		}


		public connectURL(socketName: string = "game", url: string, callBackHandler: Function, thisObject: any):void
		{
            this._connectCallBack = callBackHandler;
            this._connectThisObject = thisObject;
            this.getSocket(socketName).connectByURL(url, this, this.onSocketConnect, this.onSocketClose, this.onSocketError);
		}

		public connect(socketName: string = "game", host: string, port: number, callBackHandler: Function, thisObject: any):void
		{
			this._connectCallBack = callBackHandler;
            this._connectThisObject = thisObject;
            this.getSocket(socketName).connect(host, port, this, this.onSocketConnect, this.onSocketClose, this.onSocketError);
		}
		/**
         * 当socket发生错误的时候
         */
        private onSocketError(): void
        {
            //todo
			alert("socket IO错误");
        }
        /**
         * 当socket关闭的时候
         */
        private onSocketClose(): void
        {
            alert("socket close!!!");
        }
		/**
         *  当服务器连接上
         */
        private onSocketConnect(): void
        {
            if (this._connectCallBack != null)
            {
                this._connectCallBack.call(this._connectThisObject);
            }
            this.listenWindowError();
			alert("socket connected!!!");
        }
        /**
         * 监听全局的错误信息
         */
        private listenWindowError(): void
        {
            // window.onerror = this.sendError;
        }
		/**
        * 根据名字获取socket,没有的话创建一个新的
        */
        public getSocket(socketName: string): WebSocket
        {
            var tsocket: WebSocket = this.socketDic.getValue(socketName);
            if (tsocket == null)
            {
                tsocket = new WebSocket();
                this.socketDic.setValue(socketName, tsocket);
            }
            return tsocket;
        }
	}
}